#!/usr/bin/env python
#coding:utf-8
#__author__="ybh"
import sys,os
import requests
import json
import time
from aliyunsdkcore.client import AcsClient
from aliyunsdkcdn.request.v20141111 import DescribeDomainBpsDataRequest
basedir = '/'.join(__file__.split("/")[:-2])
sys.path.append(basedir)
os.environ['DJANGO_SETTING_MODULE']='CrazyEye.settings'
from CrazyEye import settings
import django
django.setup()
from web import models

API="https://oapi.dingtalk.com/robot/send?access_token=07133fed0a8d1c70c34c279653967514ced6f3b3de194b5824250218f9034cef"
zone_list=['cn-qingdao','cn-beijing','cn-zhangjiakou','cn-huhehaote','cn-hangzhou','cn-shanghai','cn-shenzhen']


def main():
    account_list=models.Account.objects.filter(access_id__isnull=False,product='aliyun').exclude(access_id__exact='')
    for account in account_list:
        try:
            alert_cdn(account)
        except Exception as e:
            continue

def alert_cdn(account):
    flag=0
    text = ''
    client = AcsClient(account.access_id,account.access_secret,'cn-hangzhou')
    request = DescribeDomainBpsDataRequest.DescribeDomainBpsDataRequest()
    request.set_accept_format('json')
    current_time=time.time()
    before_time=current_time-1200  #获取20分钟之前的秒数
    request.add_query_param('StartTime', time.strftime("%Y-%m-%dT%H:%MZ",time.gmtime(before_time)))
    request.add_query_param('EndTime', time.strftime("%Y-%m-%dT%H:%MZ",time.gmtime(current_time)))
    response = client.do_action_with_exception(request).decode('utf-8')
    response=json.loads(response)
    cdn_list=response['BpsDataPerInterval']['DataModule']
    count=len(cdn_list)
    for i in range(1,count):
        if float(cdn_list[i]['Value']) > 1000000 and float(cdn_list[i-1]['Value']) > 1000000 and int(cdn_list[i]['Value'])-int(cdn_list[i-1]['Value']) > 100000000:
            result=float(cdn_list[i]['Value'])/float(cdn_list[i-1]['Value'])
            if result > 1.5:
                flag+=1
            elif result < 0.5:
                flag-=1


    if flag==2 or flag==-2:
        text += "## 所在阿里云账号\n\n>%s \n\n " % account.username
        text += "## 提示\n\n 在最近20分钟内，CDN流量异常！"
        sendToDingtalk(text)



def sendToDingtalk(text):
    headers = {'content-type': 'application/json'}
    parames = {
        "msgtype": "markdown",
        "markdown": {
            "title": "CDN异常提醒",
            "text": text
        },
    }
    parames = json.dumps(parames)
    r = requests.post(API, data=parames, headers=headers)
    return r.text





if __name__=='__main__':
    time.sleep(10)
    main()
